<?php

class UserController extends Controller
{
	public $defaultAction = 'admin';
	public $menu = 'user';

	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update', 'exportExcel','synctool','showconsole','dosync'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin','phi.nguyen','jim'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new User;

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_POST['User']))
			$model->attributes=$_POST['User'];

		$this->render('admin',array(
			'searchResult'=>$model->search(),
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return User the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	public function actionExportExcel()
    {
        $criteria = new CDbCriteria;
        $criteria->with = array("referralCount");
        $criteria->order = 't.id DESC';
        $criteria->condition = 'status='.User::ACTIVE;
        $model = User::model()->findAll($criteria);
        $data = array(
            1 => array ('STT', 'HỌ VÀ TÊN', 'EMAIL', 'THỜI ĐIỂM ĐĂNG KÝ', 'ĐIỂM'),
        );
        $stt = 1;
        foreach ($model as $item) 
        {

            $data[] = array($stt++, $item->customer_name, $item->email, Yii::app()->format->formatDateTime($item->update_time), $item->referralCount);
        }
        
        
        Yii::import('application.extensions.phpexcel.JPhpExcel');
        $xls = new JPhpExcel('UTF-8', false,'Danhsach');
        $xls->addArray($data);
        $xls->generateXML('Danhsach');
    }
    
	public function actionSyncTool()
	{
			
		$this->render('synctool');
	}
	
	public function toConsole($str='')
	{
		if(!empty($str)){			
			$fp = fopen(Yii::app()->basePath.'/console', 'a');
			//file_put_contents(Yii::app()->basePath.'/console', $str, FILE_APPEND | LOCK_EX);
			fwrite($fp, $str);
			
		}
	}
	
	public function addUser($obj,$isUpdate=0){		
		      
        if($isUpdate){
        	$user=User::model()->findByAttributes(array('email'=>$obj[0]));
        	$user->status = user::ACTIVE;
        	$user->update(array('status'));
        }
        else
        {  
        	$user = new User;
	        $user->email = $obj[0];
	        $user->referral_id = $obj[7];
	        $user->customer_name = $obj[1];
	        $user->mobile = str_replace(' ', '',$obj[4]);
	        $user->address = $obj[2];
	        $user->birthday = $obj[5];
	        $user->city = $obj[6];
	        $user->status = User::ACTIVE;
	        $user->create_time = time();
	        $user->generateActivateCode();
			$user->save();
        }
        var_dump($user->mobile);
        var_dump($user->errors);
	}
	
	
	
	public function actionDosync()
	{
		$apikey = Yii::app()->params['mailchimp']['api'];
		$list_id = Yii::app()->params['mailchimp']['listid'];
		$usserver=substr($apikey,strpos($apikey, '-')+1);
		$chunk_size = 4096; //in bytes
		$url = 'http://'.$usserver.'.api.mailchimp.com/export/1.0/list?apikey='.$apikey.'&id='.$list_id;
		//$buffer=$url;
		$fp = fopen(Yii::app()->basePath.'/console', 'w');
			fwrite($fp, '');
		fclose($fp);	
		$this->toConsole('Begin get data from mailchimp...');
		
		  
		  //get all user active
		  $users = Yii::app()->db->createCommand()
		    ->select('email')
		    ->from('dtb_user u')
		
		    ->where('status=:id', array(':id'=>1))
		    ->queryColumn();
		    
		    //get all user inactive
		  $notactiveusers = Yii::app()->db->createCommand()
		    ->select('email')
		    ->from('dtb_user u')
		
		    ->where('status=:id', array(':id'=>0))
		    ->queryColumn();
		    
		    //compare
		    $lsNotinDB=array();
		    $count=0;
        /** a more robust client can be built using fsockopen **/
		$handle = @fopen($url,'r');
		$str='';
		$obj=array();
		if (!$handle) {
			$this->toConsole('<font style="color:red">failed to access url</font>');		  
		} else {
			$this->toConsole('<font style="color:blue">Done</font><br />Begin compare list user from db:<br /><br />');
		  $i = 0;
		  $header = array();
		  while (!feof($handle)) {
		    $buffer = fgets($handle, $chunk_size);
		    if (trim($buffer)!=''){
		      $obj= json_decode($buffer);
		      if ($i==0){
		        //store the header row
		        $header = $obj;
		      } else {
		        //echo, write to a file, queue a job, etc.
		        $this->toConsole('checking <b>'.$obj[0].'</b>...<br />');
		        if(!in_array($obj[0], $users)){
		        	$this->toConsole('Not found ! Adding to db...');
		        	if(in_array($obj[0], $notactiveusers))
		        		$this->addUser($obj,1);
	        		else
		        		$this->addUser($obj);
		        	
		        	$lsNotinDB[]=$obj;
		        	$count++;
		        }
		        $this->toConsole('<b>done</b><br /><br />');
		        
		      }
		      $i++;
		    }
		     
		  }
		  fclose($handle);
		  $this->toConsole('<b>'.$count.'</b> users were added to db<br />');
		  $this->toConsole('<b>ALL DONE!!!</b><br />');		  
		}
	}
	
public function actionShowconsole()
	{		
		header('Content-Type: text/event-stream');
		header('Cache-Control: no-cache');
		
		//echo Yii::app()->getBasePath();
		$str=file_get_contents(Yii::app()->basePath.'/console');
		if(!empty($str))
		{
			echo "data: ".$str;			
		}
		
		echo "\n\n";	
		flush();
		
		//read file
		
	}
}
